package com.yxuan.springboot.controller;

import com.yxuan.springboot.model.Goods;
import com.yxuan.springboot.model.Orders;
import com.yxuan.springboot.model.UserLogin;
import com.yxuan.springboot.model.UserVip;
import com.yxuan.springboot.service.GoodsService;
import com.yxuan.springboot.service.OrdersService;
import com.yxuan.springboot.service.UserLoginService;
import com.yxuan.springboot.service.UserVipService;
import com.yxuan.springboot.util.CodeUtil;
import com.yxuan.springboot.util.ResolveTokenUtil;
import com.yxuan.springboot.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @author zchao
 *   Orders控制器
 * @date 2023-05-29 14:57:28
 */
@Slf4j
@Controller
@Api(tags = "订单支付表")
@RequestMapping(value = "/orders", method = {RequestMethod.POST,RequestMethod.GET})
public class OrdersController extends BaseController<Orders>{
	
    @Autowired
    public OrdersService ordersService;
    @Autowired
    public GoodsService goodsService;
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private UserVipService userVipService;

    /**
     * @className: OrdersController.java
     * @methodName: buyGoods
     * @effect: 用户下单
     * @author: JingxuanFan
     * @date: 2023/5/29 16:16
     * @param goodsId 商品Id
    **/
    @Transactional  //将当前方法添加事务
    @ApiOperation(value = "商品下单", notes = "用户点击购买商品，创建商品订单",httpMethod = "GET")
    @GetMapping ("/buyGoods")
    @ResponseBody
    public Map<String,Object> buyGoods(HttpServletRequest request,String goodsId,String alipay_no){//传一个代理id值，加入生成的订单里
        try {


            //解析token，锁定用户
            UserLogin userLogin = ResolveTokenUtil.targetLogin(request.getHeader("token"));
            UserLogin targetUserLogin = userLoginService.findObjectByPramas(userLogin);
            Goods goods = goodsService.findTById(goodsId);

            //根据userId,goodsId以及支付状态验证订单支付状态，若未支付则返回原来的订单号
//            Orders orderInfo = this.getNoPayOrderByGoodsId(targetUserLogin.getId(),goodsId);
//            if(orderInfo!=null){
//                return ResponseMap(CodeUtil.Susser,null,orderInfo.getOrderId());
//            }

            //查询商品数量，商品是否售空
            int store = Integer.parseInt(goods.getStore()) - 1;
            if (store < 0) {
                return ResponseMap(CodeUtil.GoodsNull,"商品售空",null);
            }

            // 查询用户是否为会员，如是会员，则将会员价格变为 = 当前需购买的商品价格 减去 用户当前所拥有商品的价格（同等商品除外）
            UserVip userVip = new UserVip();
            userVip.setUserId(targetUserLogin.getId());
            UserVip userVipInfo = userVipService.findObjectByPramas(userVip);
            // 获取用户会员等级
            Integer userRank = Integer.valueOf(userVipInfo.getVipRank());

            BigDecimal lastPrice = null;
            lastPrice = goods.getPrice();
            // 查询该用户拥有的商品价格
            if(userRank == 1){
                Goods goods1 = goodsService.findTById("3");
                if(!goods1.getId().equals(goods.getId())){
                    lastPrice = goods.getPrice().subtract(goods1.getPrice());

                }
            }else if(userRank == 2){
                Goods goods1 = goodsService.findTById("4");
                if(goods.getId() == 5){
                    lastPrice = goods.getPrice().subtract(goods1.getPrice());
                }
            }






            //商品未售空，用户下单
            Date date = new Date();
            Orders orders = new Orders();
            orders.setUserLoginId(targetUserLogin.getId().toString());
            orders.setName("购买" + goods.getName() + "订单");
            orders.setGoodsId(goodsId);
            orders.setOrderId(new SimpleDateFormat("yyyyMMdd").format(date) + System.currentTimeMillis()); //设置订单编号
            orders.setTotal(lastPrice);  // 设置总价格
            orders.setCreateTime(date); // 设置添加时间
            orders.setOrdersState("0"); // 设置订单状态
            orders.setAlipayNo(alipay_no);//设置代理id
            goods.setStore(String.valueOf(store));
            //1.在订单表中添加数据 2.修改商品表中的库存数量3.返回订单号
            if(ordersService.save(orders).equals("saveSuccess") && goodsService.upd(goods).equals("updSuccess")){
                return ResponseMap(CodeUtil.Susser,null,orders.getOrderId());

            }else {
                return ResponseMap(CodeUtil.Error,"创建订单或修改库存发生错误",null);
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return ResponseMap(CodeUtil.Error,e.getMessage(),"操作错误");
        }
    }

    private Orders getNoPayOrderByGoodsId(Integer userId,String goodsId) throws Exception {

        Orders orders = new Orders();
        orders.setUserLoginId(userId.toString());
        orders.setGoodsId(goodsId);
        orders.setOrdersState("0");     //0未支付，1已支付


        Orders objectByPramas = ordersService.findObjectByPramas(orders);
        return objectByPramas;

    }



    @ResponseBody
    @RequestMapping("/searchForOrderState")
    public Result searchForOrderState(HttpServletRequest request,@RequestBody Map<String,String> map) throws Exception {
        String token = request.getHeader("token");
        UserLogin userLogin = ResolveTokenUtil.targetLogin(token);
        UserLogin targetUser = userLoginService.findObjectByPramas(userLogin);


        Orders orders = new Orders();
        orders.setUserLoginId(targetUser.getId().toString());
        orders.setOrderId(map.get("orderId"));

        Orders targetOrder = ordersService.findObjectByPramas(orders);
        Map<Object, Object> map1 = new HashMap<>();
        map1.put("orderState",targetOrder.getOrdersState());

        return new Result(map1,SUCCESSCODE);


    }

    @Transactional  //将当前方法添加事务
    @ApiOperation(value = "卡密商品下单", notes = "卡密商品下单",httpMethod = "GET")
    @GetMapping ("/buyKamil")
    @ResponseBody
    public Result buyKamil(String goodsId,String userId) throws Exception {
        return ordersService.buyKamil(goodsId,userId);
    }


}